<template>
  <div class="goodsOnline" curpage="goodsOnlineew323423432423423">
    <div class="exitExclel">
      <div class="header">
        <div class="headerContent">
          <div class="titleTxt">
            <span @click="tourShow = true"
              ><el-icon><Warning /></el-icon
            ></span>
           {{$t('merak.bath_edit')}}

            <span class="errTipMsg"> 
              （ps:全部错误条数{{ loadingParams.allErrTotal }}条,当前页面修改{{ loadingParams.allErrNumber }}条，已完成{{ loadingParams.allFinishedTotal }}条）
            </span>
          </div>
          <div class="btnBox">
            <div style="margin-right: 10px"><el-checkbox v-model="onlyErr" label="只显示错误数据" @change="onlyErrchange" /></div>
            <el-button plain @click="closeWindow">{{$t('merak.no_bath_edit')}}</el-button>
            <el-button type="primary" @click="confirmSubmit">{{$t("merak.confirm_submit")}}</el-button>
          </div>
        </div>
      </div>
      <div class="editTableDiv" style="" v-if="!headLoading">
        <editTableExcel ref="editTableRef" v-bind="tableConfig"></editTableExcel>
      </div>
    </div>
    <div>
      <cardSatus v-bind="loadingParams" @contunitEdit="contunitEditFun"></cardSatus>
    </div>
    <div class="tourDiv" v-if="tourShow">
      <div class="tourContent">
        <span class="closeSpan" @click="tourShow = false"
          ><el-icon><Close /></el-icon
        ></span>
        <div class="img_show">
          <div class="tourTitle">①单击选中，双击进行编辑</div>
          <img src="/src/assets/images/editTour/1.png" />
        </div>
        <div class="img_show">
          <div class="tourTitle">②ctrl+鼠标左键选中,右键点击获取「批量编辑」</div>
          <img src="/src/assets/images/editTour/2.png" />
        </div>
        <div class="img_show">
          <div class="tourTitle">shift+鼠标左键选中,右键点击获取「批量编辑」</div>
          <img src="/src/assets/images/editTour/3.png" />
        </div>
        <div class="img_show">
          <div class="tourTitle">④点击表头全列选中,右键点击获取「批量编辑」</div>
          <img src="/src/assets/images/editTour/4.png" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="goodsOnline">
import editTableExcel from "@/components/MerakEditTable/components/editTableExcel/index.vue"; 
// import editTableExcel from "@/components/MerakEditTable/components/editTableExcel/indexTwo.vue"; 
import qfInput from "@/components/MerakEditTable/components/a-qfInput/index.vue";
import cardSatus from "@/components/MerakEditTable/components/a-loading/index.vue";
import { ref, reactive, defineProps, onMounted, computed, nextTick } from "vue";

import { getTableFieldsApi, getTableListApi, saveTableGoodsApi } from "@/api/modules/goodsArchive/batchImport/import";
import { ResultEnum } from "@/enums/httpEnum";
import { cos } from "mathjs";
import { getLocationParams } from "@/utils/index";

import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";

const onlyErr = ref(false);
//接收url参数
const newUrl = new URL(window.location.href);
let import_id = getLocationParams(newUrl.href, "import_id");
console.log(import_id, "传入参数");

const editTableRef = ref(null);
const value2 = ref("");

const loadingParams = reactive({
  isShowProgress: false, //提交loading
  currNumber: 0, //当前提交条数
  allErrNumber: 0, //全部条数
  errorNumber: 0, //编辑完剩余错误条数
  successNumber: 0, //成功条数
  allErrTotal: 0,//所有错误条数 
  allFinishedTotal:0,//所有错误条数
});
const tourShow = ref(false);
let errInfoArr = []; //错误数组
const splitNumber = 20;
let splitIndex = 0;
const confirmSubmit = async () => {
  splitIndex = 0;
  errInfoArr = []; //每次提交都清空
  let postDataArr = editTableRef.value.saveParams();
  console.log(postDataArr);
  let allPostLen = postDataArr.length; //所有提交数组长度
  loadingParams.allErrNumber = allPostLen; //所有长度
  loadingParams.currNumber = 0; //
  loadingParams.isShowProgress = true; //打开提交弹窗

  //每10个拆分形成新数组=
  let splitedArrs = [];
  let size = splitNumber;
  for (let i = 0; i < allPostLen; i += size) {
    let splited = postDataArr.slice(i, i + size);
    splitedArrs.push(splited);
  }

  let splitLen = splitedArrs.length;
  for (let ss = 0; ss < splitLen; ss++) {
    await postDateFun(splitedArrs[ss]).then(errDataInfo => {
      splitIndex = splitIndex + splitNumber;
      loadingParams.currNumber = splitIndex; //当前提交条数

      //   //测试   所有都提交完了
      if (errDataInfo.length && Array.isArray(errDataInfo)) {
        errInfoArr = errInfoArr.concat(errDataInfo);
      }

      if (splitLen - 1 == ss) {
        //最后一组提交成功后

        loadingParams.currNumber = allPostLen; 
        loadingParams.errorNumber = errInfoArr.length; //错误条数
        loadingParams.successNumber = allPostLen - errInfoArr.length; //成功条数
        console.log(loadingParams)
      }
    });
  }

  // isShowProgress.value = true;
  // let timmer = setInterval(() => {
  //   splitIndex = splitIndex + 10;
  //   currNumber.value = splitIndex;
  //   if (splitIndex > postDataArr.length) {
  //     currNumber.value = postDataArr.length;
  //     clearInterval(timmer);
  //     return;
  //   }
  //   postData = postDataArr.slice(splitIndex, splitNumber + splitIndex);
  // }, 1000);
};

const postDateFun = dataParams => {
  //   saveTableGoodsApi({data:dataParams}).then(res=>{

  //   })
  return new Promise((resolve, reject) => {
    saveTableGoodsApi({ import_id: import_id, data: dataParams, errorColumn: onlyErr.value ? 1 : 0 })
      .then(res => {
        console.log(res);
        if (res.code == ResultEnum.SUCCESS) {
          resolve(res.data);
        }
      })
      .catch(err => {
        console.log("9999999");
        resolve(dataParams);
      });
    // setTimeout(() => {
    //   let res = {
    //     code: 2000,
    //     data: JSON.parse(JSON.stringify(tableConfig.tableData.slice(0, 5)))
    //   };
    //   if (res.code == ResultEnum.SUCCESS) {
    //     resolve(res.data);
    //   }
    //   console.log(res);
    // }, 1000);
  });
};

//继续移交
const contunitEditFun = val => {
  loadingParams.isShowProgress = false;

  if (val == "other") {
    //继续编辑其余的数据
    initData();
    return;
  }
let allCont=loadingParams.allErrTotal>100?100:loadingParams.allErrTotal;
  // Object.assign(, errInfoArr);
  if (onlyErr.value) {
    //只显示错误数据,重新请求头部
    getTableFieldsApi({ import_id: import_id, errorColumn: 1 }).then(res => {
      tableConfig.headData = res.data;
      tableConfig.tableData = errInfoArr;
      loadingParams.allErrNumber = errInfoArr.length;
      
      loadingParams.allFinishedTotal=allCont - loadingParams.allErrNumber;//所有成功的条数
      headLoading.value = true;
      nextTick(() => {
        headLoading.value = false;
      });
    });
    return;
  }
   tableConfig.tableData = errInfoArr;
  loadingParams.allErrNumber=errInfoArr.length;
  loadingParams.allFinishedTotal=allCont - loadingParams.allErrNumber;//所有成功的条数
  headLoading.value = true;
  nextTick(() => {
    headLoading.value = false;
  });
};

const onlyErrchange = e => {
  initData();
};
const closeWindow = () => {
  window.close();
  // confirmSuccessMsg({
  //   msg: "是否确认关闭当前窗口???",
  //   callback: val => {
  //     console.log(val, "成功confirm还是失败cancel");
  //     if (val == "confirm") {
  // window.close();
  //     }
  //   }
  // });
};

// 行列选中样式  当前选中样式
// 行尾部和删除
const tableConfig = reactive({
  headData: [], //表格头部数据
  tableData: [] //表格内容数据
});

let number1 = 100;
let number = 50000;

const headLoading = ref(false);
const initData = () => {
  // Object.assign(tableHeadData, []);
  headLoading.value = true;

  console.time("for");
  let headArr = [];
  let headCon = {};

  let TableNew = [];
  for (let i = 0; i < number; i++) {
    let objKey = {
      _id: "11" + i,
      number: "222",
      data: {
        spu: {
          label: "1111",
          errTip:
            "Женская Рубашка MIX, Модель Женская Рубашка MIX, Модель Женская Рубашка MIX, Модель Женская Рубашка MIX, Модель "
        },
        sku: {
          label: "1111"
        },
        qf_code: {
          label: "1111"
        },
        model: {
          label: "1111"
        },
        code: {
          label: "1111"
        },
        supplier_sku: {
          label: "1111",
          errTip: "Женская Рубашка MIX, Модель "
        },
        brand: {
          label: "1111"
        },
        num_in_packing: {
          label: "1111"
        },
        net_weight: {
          label: "1111"
        },
        qifa_color: {
          label: "1111"
        },
        supplier_color: {
          label: "1111"
        },
        manufacturer_county: {
          label: "1111"
        },
        volume: {
          label: "1111"
        },
        weight: {
          label: "1111"
        },
        size: {
          label: "1111"
        },
        category: {
          label: "1111",
          errTip: "Женская Рубашка MIX, Модель "
        },
        mk_color: {
          label: "1111",
          errTip: "Женская Рубашка MIX, Модель "
        }
      }
    };

    TableNew.push(objKey);
    // TableNew.push({
    //     index: i,
    //     date: '2016-05-03',
    //     name: 'Tom',
    //     address: 'No. 189, Grove St, Los Angeles',
    //    selection:true
    // })
  }
  // console.log(TableNew);
  getTableFieldsApi({ import_id: import_id, errorColumn: onlyErr.value ? 1 : 0 }).then(res => {
    // console.log(res.data);
    // Object.assign(tableHeadData, res.data);
    tableConfig.headData = res.data;
    getTableListApi({ import_id: import_id, errorColumn: onlyErr.value ? 1 : 0 }).then(res => {
      let newData = res.data.goods_data;
      // .map(v => {
      //   return {
      //     ...v
      //   };
      // });
      console.log(newData);
      // Object.assign(tableData, TableNew);
      //  tableConfig.tableData=TableNew;
      loadingParams.allFinishedTotal=0;
      loadingParams.allErrNumber = newData.length;
      tableConfig.tableData = newData;
      loadingParams.allErrTotal = res.data.error_count;
      headLoading.value = false;
    });
  });

  console.timeEnd("for");
};

onMounted(() => {
  initData();
});
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
